package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private RepositoryService repositoryService;

    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }

    @Override
    public void save(BpmnInfo bpmnInfo) {

        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public void update(BpmnInfo bpmnInfo) {

        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }




    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    public String uploadBpmnfile(MultipartFile file) throws IOException {

        if (file == null) {
            throw new BusinessException("文件上传已取消");
        }

        // 判断文件格式必须为 bpmn格式,否则报错
        String extension = FileUploadUtils.getExtension(file);
        if (!"bpmn".equals(extension)){
            throw  new BusinessException("上传文件格式错误");
        }
        // 获取文件存储路劲
        // 调用 FileUploadUtils.upload.upload方法
        // 传入系统文件上传目录,加上文件名
        String path = FileUploadUtils.upload(SystemConfig.getProfile(),file);
        return path;
    }
    @Override
    //流程部署
    public void deploy(String path, String info, String bpmnType) throws IOException {
        //根据路径找到文件
        File file = new File(SystemConfig.getProfile() + path);
        // 创建输入流
        FileInputStream in = new FileInputStream(file);
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        RepositoryService repositoryService = defaultProcessEngine.getRepositoryService();
        // 获取部署对象
        Deployment deploy = repositoryService.createDeployment().addInputStream(path, in).deploy();
        //获取流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploy.getId()).singleResult();
        in.close();

        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfo.setBpmnName(file.getName());
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setDeploymentId(deploy.getId());
        bpmnInfo.setInfo(info);
        bpmnInfo.setDeployTime(deploy.getDeploymentTime());

        this.save(bpmnInfo);
    }

    @Override
    public void remove(Long id) {
        BpmnInfo bpmnInfo = this.get(id);
        bpmnInfoMapper.deleteByPrimaryKey(id);

        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        ProcessDefinition processDefinition = defaultProcessEngine.getRepositoryService()
                .createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId()).singleResult();

        defaultProcessEngine.getRepositoryService().deleteDeployment(bpmnInfo.getDeploymentId());
        File file = new File(SystemConfig.getProfile(), processDefinition.getResourceName());
        if (file.exists()){
            file.delete();
        }

    }

    @Override
    public BpmnInfo queryByType(String type) {
        List<BpmnInfo> bpmnInfos = bpmnInfoMapper.queryBySelectType(type);
        BpmnInfo bpmnInfo = bpmnInfos.get(0);
        return bpmnInfo;
    }


    @Override
    public InputStream readResource(String deploymentId, String type) {
        // 创建一个空的inputStream
        InputStream inputStream = null;
        // 获取流程定义对象,后面用于获取流程定义id
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        if ("xml".equals(type)){
            // 如果是点击类型为xml 响应xml文件给前端显示
            // 根据 部署id和流程定义得到的文件名获取输入流返回给前端
            inputStream = repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());
        }else {
            // 如果是获取png文件,响应png输入流给前端
            // 新的api 用于获取流程定义里的图片文件
            DefaultProcessDiagramGenerator defaultProcessDiagramGenerator = new DefaultProcessDiagramGenerator();
            // 调用generateDiagram,根据repositoryService.getBpmnModel获取图片
            // repositoryService.getBpmnModel 里面设置流程定义id定位对应的流程定义获取图片
            // 还可以设置两个空集合,可以定义高亮节点和高亮连线,用于查看流程图的变化
            inputStream = defaultProcessDiagramGenerator.generateDiagram(repositoryService.getBpmnModel(processDefinition.getId()),
                    // 解决图片显示乱码,定义格式
                    Collections.emptyList(), Collections.emptyList(),"宋体","宋体","宋体");
        }
        return inputStream;
    }


}